<?php
namespace Data;

use Data\Drive\ToQuerySql;
use PDO;

class Page extends \Data
{
    public static function Run($sql)
    {
        if (!is_array($sql)) {
            self::Error("分页查询SQL必须为数组格式", __FILE__, __LINE__);
        }
        $page = self::getPage($sql);
        if (empty($page)) {
            return $page;
        }
        $sql['limit'] = (($page['now'] - 1) * $sql['limit']) . "," . $sql['limit'];
        $sql          = ToQuerySql::Run($sql);
        $data         = self::$db->query($sql);
        $code         = self::$db->errorCode();
        $code         = self::$db->errorCode();
        if ($code != 00000) {
            $info = self::$db->errorInfo();
            self::Error(json_encode($info) . "\r\n" . $sql, __FILE__, __LINE__);
        } else if (!$data || $data->rowCount() == 0) {
            return null;
        }
        return ["data" => $data->fetchAll(PDO::FETCH_ASSOC), "page" => $page];
    }

    //获取分页效果
    protected static function getPage($sql)
    {
        $limit        = $sql['limit'];
        $sql['field'] = "count(-1) as num";
        unset($sql['limit']);
        unset($sql['order']);
        $sql  = ToQuerySql::Run($sql);
        $data = self::$db->query($sql);
        $code = self::$db->errorCode();
        if ($code != 00000) {
            $info = self::$db->errorInfo();
            self::Error(json_encode($info) . "\r\n" . $sql, __FILE__, __LINE__);
        } else if (!$data || $data->rowCount() == 0) {
            return null;
        }
        $data                                         = $data->fetchAll(PDO::FETCH_ASSOC);
        $page                                         = [];
        $page['count']                                = $data[0]['num']; //总条数
        $page['total']                                = ceil($page['count'] / $limit); // 总页数
        $page['now']                                  = isset($_GET['p']) ? ($_GET['p'] - 0) : 1; //当前页
        $page['now'] > $page['total'] && $page['now'] = $page['total'];
        $page['now'] < 1 && $page['now']              = 1;
        $page['prev']                                 = $page['now'] - 1; //上一页
        $page['next']                                 = $page['now'] + 1; //下一页
        if ($page['total'] <= 7) {
            $page['num'] = range(1, $page['total']);
        } elseif ($page['now'] <= 4) {
            $page['num'] = [1, 2, 3, 4, 5, '...', $page['total']];
        } elseif (($page['total'] - $page['now']) <= 3) {
            $page['num'] = [1, '...', $page['total'] - 4, $page['total'] - 3, $page['total'] - 2, $page['total'] - 1, $page['total']];
        } else {
            $page['num'] = [1, '...', $page['now'] - 1, $page['now'], $page['now'] + 1, '...', $page['total']];
        }
        return $page;
    }
}
